#!/usr/bin/env bash
# Summary: Display the full path to an executable
# Usage: sbtenv which <command>
#
# Displays the full path to the executable that sbtenv will invoke when
# you run the given command.

set -e
test -n "${SBTENV_DEBUG}" && set -x

# Provide sbtenv completions
if [ "${1}" = "--complete" ]; then
  exec sbtenv shims --short
fi

expand_path() {
  if [ ! -d "${1}" ]; then
    return 1
  fi

  local cwd="$(pwd)"
  cd "${1}"
  pwd
  cd "${cwd}"
}

remove_from_path() {
  local path_to_remove="$(expand_path "${1}")"
  local result=""

  if [ -z "${path_to_remove}" ]; then
    echo "${PATH}"
    return
  fi

  local paths
  IFS=: paths=(${PATH})

  for path in "${paths[@]}"; do
    path="$(expand_path "${path}" || true)"
    if [ -n "${path}" ] && [ "${path}" != "${path_to_remove}" ]; then
      result="${result}${path}:"
    fi
  done

  echo "${result%:}"
}

SBTENV_VERSION="$(sbtenv-version-name)"
SBTENV_COMMAND="${1}"

if [ -z "${SBTENV_COMMAND}" ]; then
  sbtenv-help --usage which >& 2
  exit 1
fi

if [ "${SBTENV_VERSION}" = "system" ]; then
  PATH="$(remove_from_path "${SBTENV_ROOT}/shims")"
  SBTENV_COMMAND_PATH="$(command -v "${SBTENV_COMMAND}" || true)"
else
  SBTENV_COMMAND_PATH="${SBTENV_ROOT}/versions/${SBTENV_VERSION}/sbt/bin/${SBTENV_COMMAND}"
fi

OLDIFS="${IFS}"
IFS=$'\n' scripts=(`sbtenv-hooks which`)
IFS="${OLDIFS}"
for script in "${scripts[@]}"; do
  source "${script}"
done

if [ -x "${SBTENV_COMMAND_PATH}" ]; then
  echo "${SBTENV_COMMAND_PATH}"
else
  echo "sbtenv: ${SBTENV_COMMAND}: command not found" >& 2

  versions="$(sbtenv-whence "${SBTENV_COMMAND}" || true)"
  if [ -n "${versions}" ]; then
    { echo ""
      echo "The \`${1}\` command exists in these sbt versions:"
      echo "${versions}" | sed 's/^/  /g'
      echo ""
    } >& 2
  fi

  exit 127
fi

